package ua.races.command.implementation;

import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import ua.races.relultObjects.FullRace;
import ua.races.vo.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.sql.SQLException;
import java.sql.Date;
import java.util.ArrayList;

public class PostingToDbCommand implements ServletCommand {
    private static final Logger log = Logger.getLogger(PostingToDbCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        RacesDaoImpl dao;
        dao = (RacesDaoImpl) context.getAttribute("DAO");
        BetType betType = null;
        Race race = null;
        FullRace fullRace = null;
        Double betValue = null;
        Client client = null;
        Bet bet = null;
        String firstHorse = null;
        String secondHorse = null;
        String thirdHorse = null;
        // flag is just for business logic
        boolean repeat = false;
        String redirectUrl = null;
        String message = null;


        try {
            message = "Sorry, you had inputted wrong data " +
                    "and your bet has not been successfully added (((";
            redirectUrl = req.getHeader("referer");

            betType = dao.findBetTypeById(Long.parseLong(req.getParameter("betTypeId")));
            race = dao.findRaceById(Long.parseLong(req.getParameter("raceId")));
            fullRace = dao.getFullRaces(race);
            betValue = Double.valueOf(req.getParameter("betValue"));
            firstHorse = req.getParameter("firstHorse");
            secondHorse = req.getParameter("secondHorse");
            thirdHorse = req.getParameter("thirdHorse");
            client = (Client) req.getSession().getAttribute("client");

            bet = new Bet();
            bet.setBetTypeId(betType.getBetTypeId());
            bet.setBetDate(new Date(java.lang.System.currentTimeMillis()));
            bet.setBetValue(betValue);
            bet.setClientId(client.getClientId());
            bet.setRaceId(race.getRaceId());
            bet.setResult(null);

            for (Horse h : fullRace.getHorses()) {
                repeat = false;
                if (h.getHorseName().equals(firstHorse)) {
                    bet.setFirstHorse(h.getHorseId());
                    repeat = true;
                }
                if (h.getHorseName().equals(secondHorse)) {
                    bet.setSecondHorse(h.getHorseId());
                    if (repeat) {
                        throw new IllegalArgumentException("Client has chosen one horse several times!!!");
                    } else {
                        repeat = true;
                    }
                }
                if (h.getHorseName().equals(thirdHorse)) {
                    bet.setThirdHorse(h.getHorseId());
                    if (repeat) {
                        throw new IllegalArgumentException("Client has chosen one horse several times!!!");
                    }
                }
            }
            dao.addNewBet(bet);
            message = "Your bet has been successfully added";
            redirectUrl = "/prepareClient.do";

        } catch (SQLException e) {
            log.error(e);
        } catch (Throwable e) {
            log.error(e);
        } finally {
            try {
                req.setAttribute("message", message);
                req.setAttribute("URL", redirectUrl);
                context.getRequestDispatcher("/redirection.jsp").forward(req, resp);
            } catch (ServletException e) {
                log.error(e);
            } catch (IOException e) {
                log.error(e);
            }
        }

    }
}
